import { effect, track, trigger } from "./effect.js";
import { TriggerOpTypes } from "./operations.js";

function nomalizeParameter(getterOrOptions) {
  let getter, setter;
  if (typeof getterOrOptions === "function") {
    getter = getterOrOptions;
    setter = (v) => {
      throw new Error("computed is readonly");
    };
  } else {
    getter = getterOrOptions.get;
    setter = getterOrOptions.set;
  }
  return { getter, setter };
}
export function computed(getterOrOptions) {
  const { getter, setter } = nomalizeParameter(getterOrOptions);
  let value,
    dirty = true;
  const effectFn = effect(getter, {
    lazy: true,
    scheduler(){
        dirty = true;
        trigger(computedObj,TriggerOpTypes.Set,"value");
    }
  });
  const computedObj = {
    get value() {
      track(computedObj,TriggerOpTypes.Get, "value");
      if (dirty) {
        value = effectFn();
        dirty = false;
      }
      return value;
    },
    set value(newValue) {
      setter(newValue);
    }
  };
  console.log(computedObj);
  return computedObj;
}
